// 博客图片管理API服务 - 支持MongoDB
const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const Authorization = require('../middleware/authorization');
const { getMongoDB } = require('../config/multi-database');

// 获取博客图片列表
router.get('/blog-images', async (req, res) => {
    try {
        const { 
            page = 1, 
            limit = 20, 
            blogId, 
            isActive = true 
        } = req.query;

        const db = getMongoDB();
        const skip = (page - 1) * limit;
        
        // 构建查询条件
        const query = {};
        if (isActive !== undefined) query.isActive = isActive === 'true';
        if (blogId) query.blogId = blogId;
        
        // 获取总数
        const total = await db.collection('blog_images').countDocuments(query);
        
        // 获取数据
        const cursor = db.collection('blog_images')
            .find(query)
            .sort({ sortOrder: 1, createdAt: -1 })
            .skip(skip)
            .limit(parseInt(limit));
        
        const data = await cursor.toArray();
        
        res.json({
            success: true,
            data: data,
            pagination: {
                page: parseInt(page),
                limit: parseInt(limit),
                total,
                totalPages: Math.ceil(total / limit)
            }
        });
    } catch (error) {
        console.error('获取博客图片列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取博客图片列表失败'
        });
    }
});

// 获取特定博客的图片（前端使用）
router.get('/blog-images/blog/:blogId', async (req, res) => {
    try {
        const { blogId } = req.params;
        const { limit = 20 } = req.query;

        const db = getMongoDB();
        
        const cursor = db.collection('blog_images')
            .find({ 
                blogId: blogId, 
                isActive: true 
            })
            .sort({ sortOrder: 1, createdAt: -1 })
            .limit(parseInt(limit));
        
        const data = await cursor.toArray();
        
        res.json({
            success: true,
            data: data
        });
    } catch (error) {
        console.error('获取博客图片失败:', error);
        res.status(500).json({
            success: false,
            message: '获取博客图片失败'
        });
    }
});

// 获取博客封面图
router.get('/blog-images/blog/:blogId/cover', async (req, res) => {
    try {
        const { blogId } = req.params;

        const db = getMongoDB();
        
        const coverImage = await db.collection('blog_images').findOne({ 
            blogId: blogId,
            isCover: true,
            isActive: true
        });
        
        if (!coverImage) {
            // 如果没有封面图，返回第一个启用的图片
            const fallbackImage = await db.collection('blog_images').findOne({ 
                blogId: blogId,
                isActive: true
            });
            
            return res.json({
                success: true,
                data: fallbackImage || null
            });
        }

        res.json({
            success: true,
            data: coverImage
        });
    } catch (error) {
        console.error('获取博客封面图失败:', error);
        res.status(500).json({
            success: false,
            message: '获取博客封面图失败'
        });
    }
});

// 获取博客图片详情
router.get('/blog-images/:id', authenticateToken, async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const blogImage = await db.collection('blog_images').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!blogImage) {
            return res.status(404).json({
                success: false,
                message: '博客图片不存在'
            });
        }

        res.json({
            success: true,
            data: blogImage
        });
    } catch (error) {
        console.error('获取博客图片详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取博客图片详情失败'
        });
    }
});

// 创建博客图片
router.post('/blog-images', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const blogImageData = {
            ...req.body,
            createdBy: req.user.userId,
            createdAt: new Date(),
            updatedAt: new Date()
        };

        // 验证必填字段
        if (!blogImageData.name || !blogImageData.imageUrl || !blogImageData.blogId) {
            return res.status(400).json({
                success: false,
                message: '图片名称、URL和博客ID为必填项'
            });
        }

        // 设置默认值
        if (!blogImageData.sortOrder) blogImageData.sortOrder = 0;
        if (blogImageData.isActive === undefined) blogImageData.isActive = true;
        if (blogImageData.isCover === undefined) blogImageData.isCover = false;

        // 如果是封面图，检查是否已存在封面图
        if (blogImageData.isCover) {
            const existingCoverImage = await db.collection('blog_images').findOne({ 
                blogId: blogImageData.blogId, 
                isCover: true 
            });
            
            if (existingCoverImage) {
                return res.status(400).json({
                    success: false,
                    message: '该博客已存在封面图，请先取消其他封面图设置'
                });
            }
        }

        const result = await db.collection('blog_images').insertOne(blogImageData);
        const blogImage = { ...blogImageData, _id: result.insertedId };

        res.status(201).json({
            success: true,
            message: '博客图片创建成功',
            data: blogImage
        });
    } catch (error) {
        console.error('创建博客图片失败:', error);
        res.status(500).json({
            success: false,
            message: '创建博客图片失败'
        });
    }
});

// 更新博客图片
router.put('/blog-images/:id', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const blogImage = await db.collection('blog_images').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!blogImage) {
            return res.status(404).json({
                success: false,
                message: '博客图片不存在'
            });
        }

        const updateData = {
            ...req.body,
            updatedAt: new Date()
        };

        // 如果是封面图，检查是否已存在其他封面图
        if (updateData.isCover === true) {
            const existingCoverImage = await db.collection('blog_images').findOne({ 
                blogId: blogImage.blogId, 
                isCover: true,
                _id: { $ne: new ObjectId(req.params.id) }
            });
            
            if (existingCoverImage) {
                return res.status(400).json({
                    success: false,
                    message: '该博客已存在封面图，请先取消其他封面图设置'
                });
            }
        }

        const result = await db.collection('blog_images').findOneAndUpdate(
            { _id: new ObjectId(req.params.id) },
            { $set: updateData },
            { returnDocument: 'after' }
        );

        res.json({
            success: true,
            message: '博客图片更新成功',
            data: result.value
        });
    } catch (error) {
        console.error('更新博客图片失败:', error);
        res.status(500).json({
            success: false,
            message: '更新博客图片失败'
        });
    }
});

// 删除博客图片
router.delete('/blog-images/:id', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const blogImage = await db.collection('blog_images').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!blogImage) {
            return res.status(404).json({
                success: false,
                message: '博客图片不存在'
            });
        }

        const result = await db.collection('blog_images').deleteOne({ 
            _id: new ObjectId(req.params.id) 
        });

        if (result.deletedCount > 0) {
            res.json({
                success: true,
                message: '博客图片删除成功'
            });
        } else {
            res.status(500).json({
                success: false,
                message: '博客图片删除失败'
            });
        }
    } catch (error) {
        console.error('删除博客图片失败:', error);
        res.status(500).json({
            success: false,
            message: '删除博客图片失败'
        });
    }
});

// 设置博客封面图
router.post('/blog-images/:id/set-cover', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const blogImage = await db.collection('blog_images').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!blogImage) {
            return res.status(404).json({
                success: false,
                message: '博客图片不存在'
            });
        }

        const session = db.client.startSession();
        
        try {
            session.startTransaction();
            
            // 取消该博客的所有封面图设置
            await db.collection('blog_images').updateMany(
                { 
                    blogId: blogImage.blogId, 
                    isCover: true 
                },
                { $set: { isCover: false, updatedAt: new Date() } },
                { session }
            );
            
            // 设置当前图片为封面图
            const result = await db.collection('blog_images').findOneAndUpdate(
                { _id: new ObjectId(req.params.id) },
                { $set: { 
                    isCover: true, 
                    updatedAt: new Date() 
                } },
                { returnDocument: 'after', session }
            );
            
            await session.commitTransaction();
            
            res.json({
                success: true,
                message: '博客封面图设置成功',
                data: result.value
            });
        } catch (error) {
            await session.abortTransaction();
            throw error;
        } finally {
            await session.endSession();
        }
    } catch (error) {
        console.error('设置博客封面图失败:', error);
        res.status(500).json({
            success: false,
            message: '设置博客封面图失败'
        });
    }
});

// 批量更新博客图片排序
router.post('/blog-images/sort', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const { sortData } = req.body;
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');

        if (!Array.isArray(sortData) || sortData.length === 0) {
            return res.status(400).json({
                success: false,
                message: '排序数据无效'
            });
        }

        const session = db.client.startSession();
        
        try {
            session.startTransaction();
            
            for (const item of sortData) {
                await db.collection('blog_images').updateOne(
                    { _id: new ObjectId(item.id) },
                    { $set: { sortOrder: item.sortOrder, updatedAt: new Date() } },
                    { session }
                );
            }
            
            await session.commitTransaction();
            
            res.json({
                success: true,
                message: '博客图片排序更新成功'
            });
        } catch (error) {
            await session.abortTransaction();
            throw error;
        } finally {
            await session.endSession();
        }
    } catch (error) {
        console.error('批量更新博客图片排序失败:', error);
        res.status(500).json({
            success: false,
            message: '批量更新博客图片排序失败'
        });
    }
});

// 获取博客图片统计
router.get('/blog-images/stats', authenticateToken, async (req, res) => {
    try {
        const db = getMongoDB();
        
        const pipeline = [
            {
                $group: {
                    _id: '$blogId',
                    imageCount: { $sum: 1 },
                    activeCount: {
                        $sum: { $cond: [{ $eq: ['$isActive', true] }, 1, 0] }
                    },
                    coverImageCount: {
                        $sum: { $cond: [{ $eq: ['$isCover', true] }, 1, 0] }
                    }
                }
            },
            {
                $project: {
                    blogId: '$_id',
                    imageCount: 1,
                    activeCount: 1,
                    coverImageCount: 1,
                    _id: 0
                }
            },
            { $sort: { imageCount: -1 } }
        ];
        
        const stats = await db.collection('blog_images').aggregate(pipeline).toArray();
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取博客图片统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取博客图片统计失败'
        });
    }
});

// 获取博客图片类型统计
router.get('/blog-images/stats/types', authenticateToken, async (req, res) => {
    try {
        const db = getMongoDB();
        
        const pipeline = [
            {
                $group: {
                    _id: '$imageType',
                    count: { $sum: 1 },
                    activeCount: {
                        $sum: { $cond: [{ $eq: ['$isActive', true] }, 1, 0] }
                    }
                }
            },
            {
                $project: {
                    imageType: '$_id',
                    count: 1,
                    activeCount: 1,
                    _id: 0
                }
            },
            { $sort: { count: -1 } }
        ];
        
        const stats = await db.collection('blog_images').aggregate(pipeline).toArray();
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取博客图片类型统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取博客图片类型统计失败'
        });
    }
});

module.exports = router;